<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style type="text/css">
    * {
        padding: 0;
        margin: 0;
    }
    
    h2 {
        margin-bottom: 20px;
    }
    
    #container {
        width: 500px;
        text-align: center;
        margin: 0 auto;
        font-family: "微软雅黑";
        margin-top: 50px;
    }
    
    .selectContainer {
        position: relative;
    }
    
    .selectInput {
        width: 200px;
        height: 25px;
        border-style: none;
        border: 1px solid #999;
        border-radius: 5px;
        padding: 0 3px;
    }
    
    .picture_click {
        background: url(img/select-default.png) no-repeat;
        opacity: 1;
        width: 15px;
        height: 8px;
        position: absolute;
        top: 10px;
        right: 125px;
    }
    
    .picture_click:hover {
        background-image: url(img/select-hover.png);
    }
    
    .selectList {
        width: 206px;
        height: 212px;
        overflow-y: scroll;
        text-align: left;
        margin: 0 172px;
        border: 1px solid #ccc;
        display: none;
        position: relative;
    }
    
    .selectList div {
        cursor: pointer;
    }
    
    .nullcon {
        display: none;
        text-align: center;
        padding: 10px;
        word-break: break-all;
    }
</style>
<script src="./jquery-1.12.4.min.js"></script>

<body>
    <div id="container">
        <h2>模糊搜索</h2>
        <div id="cityContainer" class="selectContainer">
            <label>PN：</label>
            <input type="text" placeholder="请输入公司名称" list="cityList" class="selectInput" name="cityName" id="cityName" value="" onfocus="fuzzySearch.call(this, 'cityList')" />
            <div class="picture_click dropDowns" style=""></div>
            <div id="cityList" class="selectList">

            </div>
        </div>
    </div>
</body>
<script type="text/javascript">
    function fuzzySearch(listId) {
        var that = this;
        //初始化下拉框
        initSearchInput(that, listId);
        var listArr = [{
            'eleId': '01',
            eleName: '测试公司'
        }, {
            'eleId': '02',
            eleName: '出纳测试公司1'
        }, {
            'eleId': '03',
            eleName: '期间设置公司'
        }, {
            'eleId': '04',
            eleName: '演示公式'
        }, {
            'eleId': '05',
            eleName: '公司11'
        }, {
            'eleId': '06',
            eleName: 'HFY测试公司'
        }, {
            'eleId': '07',
            eleName: '测试公司2'
        }, {
            'eleId': '08',
            eleName: '中餐饮有限公司'
        }, {
            'eleId': '09',
            eleName: '烤匠烤鱼餐厅'
        }, {
            'eleId': '10',
            eleName: '呷哺呷哺北京1'
        }, {
            'eleId': '11',
            eleName: '呷哺呷哺北京2店'
        }, {
            'eleId': '12',
            eleName: '呷哺呷哺北京3店'
        }, {
            'eleId': '13',
            eleName: '肯德基'
        }, {
            'eleId': '14',
            eleName: '麦当劳'
        }, {
            'eleId': '15',
            eleName: '必胜客'
        }, {
            'eleId': '16',
            eleName: '麦当劳222'
        }]

        var aa = $('#' + listId);

        //遍历数组，创建元素默认显示
        $('#' + listId).html('');
        $.each(listArr, function(index, item) {
            var divStr = '<div id=' + item.eleId + '>' + item.eleName + '</div>';

            $('#' + listId).append(divStr);
            console.log($('#' + listId));
        })
        $('#' + listId).append('<div id="nullcon" class="nullcon">没有找到内容</div>');

        //current用来记录当前元素的索引值
        var current = 0;
        //匹配文本框中输入的字符串
        var showList = searchText(that, listArr, listId);

        bindFun();

        //为文本框绑定键盘引起事件
        $(this).keyup(function(e) {
            //如果输入空格自动删除
            this.value = this.value.replace(' ', '');
            //列表框显示
            $('#' + listId).show();
            if (e.keyCode == 38) {
                //up
                console.log('up');
                current--;
                if (current <= 0) {
                    current = 0;
                }
                console.log(current);
            } else if (e.keyCode == 40) {
                //down
                console.log('down');
                current++;
                if (current >= showList.length) {
                    current = showList.length - 1;
                }
                console.log(current);

            } else if (e.keyCode == 13) {
                //enter
                console.log('enter');
                //如果按下回车，将此列表项的内容填充到文本框中
                $(that).val(showList[current].eleName);
                //下拉框隐藏
                $('#' + listId).hide();
            } else {
                //other
                console.log('other');
                showList = searchText(that, listArr, listId);
                current = 0;
            }


            //设置当前项的背景色及位置
            if (showList && showList.length != 0) {
                $.each(showList, function(index, item) {
                    if (index == current) {
                        $('#' + item.eleId).css('background', '#eee');
                        $('#' + listId).scrollTop($('#' + item.eleId).get(0).offsetTop);
                    } else {
                        $('#' + item.eleId).css('background', '');
                    }
                })
            }
            //设置下拉框的高度
            //212为列表框的最大高度
            if (showList && showList.length != 0) {
                if (212 > $('#' + listId).find('div').eq(0).height() * showList.length) {
                    $('#' + listId).height($('#' + listId).find('div').eq(0).height() * showList.length);
                } else {
                    $('#' + listId).height(212);
                }
            }
        })
    }

    //绑定事件
    function bindFun() {
        //给下拉箭头绑定点击事件  点击下拉箭头显示/隐藏对应的列表
        //输入框的类名为selectInput
        //下拉箭头的类名为picture_click、dropDowns
        //下拉列表的类名为selectList
        for (var i = 0; i < $('.picture_click').length; i++) {
            $('.picture_click').eq(i).click(function() {
                $(this).parent().find('.selectList').toggle();
            })
        }

        //为列表中的每一项绑定鼠标经过事件
        $('.selectList div').mouseenter(function() {
            $(this).css("background", "#eee").siblings().css("background", "");
        });
        //为列表中的每一项绑定单击事件
        $('.selectList div').bind('click', function() {
            //文本框为选中项的值
            $(this).parent().parent().find('.selectInput').val($(this).html());
            //下拉框隐藏
            $(this).parent().hide();
        });
    }


    function initSearchInput(that, listId) {

        //点击下拉框外部的时候使下拉框隐藏
        var dropDowns = document.getElementsByClassName('dropDowns');
        var selectList = document.getElementsByClassName('selectList');

        document.body.onclick = function(e) {
            e = e || window.event;
            var target = e.target || e.srcElement;
            console.info('target', target);
            console.info('that', that);
            console.info('===', target == that)
            if (target == that) {
                $('#' + listId).show();
            } else {
                for (var i = 0; i < dropDowns.length; i++) {
                    if (target != dropDowns[i] && target != selectList[i]) {
                        selectList[i].style.display = 'none';
                    }
                }
            }

        }
    }


    function searchText(that, listArr, listId) {
        //文本框中输入的字符串
        var searchVal = $(that).val();
        var showList = [];
        if (showList.length == 0 && !$(that).val()) {
            //showList为列表中和所输入的字符串匹配的项
            showList = listArr;
        }

        if (searchVal) {
            //将和所输入的字符串匹配的项存入showList
            //将匹配项显示，不匹配项隐藏
            $.each(listArr, function(index, item) {
                if (item.eleName.indexOf(searchVal) != -1) {
                    $('#' + item.eleId).css('display', 'block');
                    showList.push(item);
                } else {
                    $('#' + item.eleId).css('display', 'none');
                }
            })
        } else {
            showList = listArr;
            $.each(listArr, function(index, item) {
                $('#' + item.eleId).css('display', 'block');
            })
            $(that).siblings('.selectList').find('#nullcon').hide();
        }
        // 如果用户输入的关键字匹配不到，提示用户不存在
        if (showList.length == 0 && $(that).val()) {
            $('#' + listId).height(50);
            $(that).siblings('.selectList').find('#nullcon').html('没有找到"' + $(that).val() + '"的内容').show();
        }

        console.log('showList', showList);

        return showList;
    }
</script>

</html>